package com.example.htmlToPdf;

import java.io.*;
import java.nio.charset.Charset;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;

@SpringBootApplication
@RestController
public class HtmlToPdfApplication {

    private Logger log = LoggerFactory.getLogger(HtmlToPdfApplication.class);

    public static void main(String[] args) {
        SpringApplication.run(HtmlToPdfApplication.class, args);
    }

    @GetMapping("/genpdf/{fileName}")
    HttpEntity<byte[]> createPdf(
            @PathVariable("fileName") String fileName) throws IOException {

        /* first, get and initialize an engine */
        VelocityEngine ve = new VelocityEngine();
        ve.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8");
        ve.setProperty(Velocity.INPUT_ENCODING, "UTF-8");//指定编码格式，避免生成模板就造成乱码，影响到转pdf后的文件
        ve.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");

        /* next, get the Template */
        ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        ve.init();
        Template t = ve.getTemplate("templates/helloworld.vm");
        /* create a context and add data */
        VelocityContext context = new VelocityContext();
        context.put("name", "World");
        /* now render the template into a StringWriter */
        StringWriter writer = new StringWriter();

        t.merge(context, writer);
        /* show the World */
        System.out.println(writer.toString());

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        baos = generatePdf(writer.toString());

        HttpHeaders header = new HttpHeaders();
        header.setContentType(MediaType.APPLICATION_PDF);
        header.set(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=" + fileName.replace(" ", "_"));
        header.setContentLength(baos.toByteArray().length);

        return new HttpEntity<>(baos.toByteArray(), header);

    }

    public ByteArrayOutputStream generatePdf(String html) {

        String pdfFilePath = "";
        PdfWriter pdfWriter = null;

        // create a new document
        Document document = new Document();
        try {

            document = new Document();
            // document header attributes
            document.addAuthor("Kinns");
            document.addAuthor("Kinns123");
            document.addCreationDate();
            document.addProducer();
            document.addCreator("kinns123.github.io");
            document.addTitle("HTML to PDF using itext");
            document.setPageSize(PageSize.LETTER);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PdfWriter.getInstance(document, baos);

            // open document
            document.open();

            //设置中文字体
            //加载字体
            XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider() {

//                @Override
//                public Font getFont(String fontname, String encoding, boolean embedded, float size, int style, BaseColor color) {
//                    log.debug("fontname:{},size:{},encoding:{},embedded:{},style:{},color:{}", fontname, size, encoding, embedded, style, color == null ? null : color.toString());
////                    this.defaultEncoding = "UTF-8";
////                    encoding = "UTF-8";
////                    //你的字体文件的位置
////                    //这里把所有字体都设置为宋体了,可以根据fontname的值设置字体
////                    String yaHeiFontName = "C:\\Windows\\Fonts\\symbol.ttf";
////                    //如果是ttc需要这一行,ttf不需要
//////                    yaHeiFontName += ",1";
////                    Font yaHeiFont;
////                    Font font = null;
////                    try {
////                        super.getFont(yaHeiFontName,"UTF-8",)
////                        font = new Font(com.itextpdf.text.pdf.BaseFont.createFont(yaHeiFontName, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED));
////                        font.setStyle(style);
////                        font.setColor(color);
////                        if (size > 0) {
////                            font.setSize(size);
////                        }
////                    } catch (DocumentException e) {
////                        e.printStackTrace();
////                    } catch (IOException e) {
////                        e.printStackTrace();
////                    }
////                    return font;
//
//
//                }
                @Override
                public Font getFont(String fontname, String encoding, float size, int style) {
                    String yaHeiFontName = "C:\\Windows\\Fonts\\symbol.ttf";
                    return super.getFont(yaHeiFontName, "UTF-8", size, style);
                }
            };


            XMLWorkerHelper xmlWorkerHelper = XMLWorkerHelper.getInstance();
            xmlWorkerHelper.getDefaultCssResolver(true);
            InputStream in = new ByteArrayInputStream(html.getBytes("UTF-8"));
            XMLWorkerHelper.getInstance().parseXHtml(pdfWriter, document, in, Charset.forName("UTF-8"), fontProvider);

            // close the document
            document.close();
            System.out.println("PDF generated successfully");
            String s = baos.toString("UTF-8");
            return baos;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    @GetMapping("/msg")
    public String printMesssage() {
        return "this is the message中文中文";
    }

}
